# selenium的各种工具
from selenium import webdriver  
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait  
from selenium.webdriver.support import expected_conditions as EC 
from selenium.common.exceptions import TimeoutException

import logging  
logging.basicConfig(level=logging.INFO)  


# 初始化 webdriver
def initWebDriver(chromedriverpath):
    ser = Service()	
    ser.executable_path = chromedriverpath

    options=Options()
    options.add_argument('--incognito')
    options.add_argument('--disable-infobars')

    driver=webdriver.Chrome(options=options,service=ser)  

    return driver

def closeDriver(driver):
    if driver is not None:
        driver.quit()

# 根据cssSelector 获取页面元素                
def findElement(driver, by=By.CSS_SELECTOR, value=None, innerText=None,waitTime=10):
    logging.debug(f'查找元素 {value}')
    
    if driver is None:
        logging.warn('参数driver不允许为空')
        return None 
    
    if value is None:
        logging.warn('参数value不允许为空')
        return None

    print(f"waitTime is {waitTime} ")

    findElems = None

    if waitTime==None or waitTime<=0:
        
        
        elems=driver.find_elements(by=by, value=value)
        if len(elems)==0:
            return  None
        else:
            findElems = elems
    else:
        try:
            elems=WebDriverWait(driver, waitTime).until( EC.presence_of_all_elements_located(
                (by , value) ))
            
            if len(elems)==0:
                return None
            else:
                findElems = elems
        except TimeoutException as e:
            logging.error(f'数据请求超时 value= {value} , innerText = {innerText}')
            return None

    # 如果提供了innerText参数
    if innerText is not None and innerText!='':
        for elem1 in findElems:
            if elem1.text != innerText:
                findElems.remove(elem1)
    
    if len(findElems)==0:
        return None
    elif len(findElems) ==1:
        return findElems[0]
    else:
        return findElems
    
    

        
        
        



